/**
 * Created by ying on 16-7-22.
 */
$(document).ready(function(){
    get_product_list();
    show_cart_count();
    add_click_event();
    get_item();
});
function show_cart_count(){
    var count=localStorage.getItem("sum_count")||0;
    $("#sum_count").html(count);
}
function add_cart_count(){
    var count=$("#sum_count").html()||0;
    count++;
    $("#sum_count").html(count);
    localStorage.setItem("sum_count",count);
}
function add_click_event (){
    $("td button").click(function(){
        add_cart_count();
    });
}
function get_product_list(){
    var product_data=[
        {classification:"饮料",name:"可口可乐",price:"3",unit:"瓶"},
        {classification:"饮料",name:"雪碧",price:"3",unit:"瓶"},
        {classification:"水果",name:"苹果",price:"5.5",unit:"斤"},
        {classification:"水果",name:"荔枝",price:"15",unit:"斤"},
        {classification:"生活用品",name:"电池",price:"2",unit:"个"},
        {classification:"食品",name:"方便面",price:"4.5",unit:"袋"}
    ];
    $("#form").tmpl(product_data).appendTo("#product_list");
}
function get_item(){
   var items=JSON.parse(localStorage.getItem("data"));
    var goods_item=items ||[];
    var new_name=JSON.parse(localStorage.getItem("name"))||[];
    $("td").click(function(){
        var classification=$(this).parents("tr").find("td").eq(0).text();
        var name=$(this).parents("tr").find("td").eq(1).text();
        var price=$(this).parents("tr").find("td").eq(2).text();
        var unit=$(this).parents("tr").find("td").eq(3).text();
        var item={classification:classification, name:name, price:price, unit:unit,count:1}
        if(new_name.indexOf(item.name)==-1){
            new_name.push(item.name);
            localStorage.setItem("name",JSON.stringify(new_name));
            goods_item.push(item);
        }else{
            goods_item=JSON.parse(localStorage.getItem("data"))
            _.each(goods_item,function(key){
                if(key.name==item.name){
                    key.count++;
                }
            })
        }
        localStorage.setItem("data",JSON.stringify(goods_item));
        goods_item=JSON.parse(localStorage.getItem("data"))
    });
}